<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\facade\View;
use think\response\Json;
use addons\Builder\facade\Builder;

class Role extends Base
{

    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Role';

    protected string $validate = 'Role';

    //关联模型
    protected array $hasOne;


    public function index(): string
    {
        return Builder::Table()
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addColumn(['field' => 'title', 'title' => '角色名', 'modify' => '1,input'])
            ->addColumn(['field' => 'explain', 'title' => '角色描述', 'modify' => '2,input'])
            ->addColumn(['field' => 'create_time', 'title' => '创建时间'])
            ->addColumn(['field' => 'update_time', 'title' => '更新时间'])
            ->addColumn(['field' => 'status', 'title' => '状态', 'templet' => '#status', 'width' => 120])
            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作'])
            ->addTopButtons(['add' => ['size' => '50%']])
            ->addRightButtons([
                'give'    => [
                    'title' => '分配权限',
                    'url'   => url('role/give')->build(),
                    'event' => '_openNewPage',
                    'size'  => '50%',
                    'site'  => 'r'
                ], 'edit' => ['size' => '50%'], 'delete'])
            ->addSearch([
                ['title', '角色名', 'input', '', '', '', 'like']
            ])
            ->addSwitchTool([['name' => 'status', 'pk' => $this->pk, 'text' => '开启|关闭']])
            ->addExtraHtml(['role'])
            ->fetch();
    }

    /**
     * @param $id
     * @return string|Json
     */
    public function give($id)
    {
        if ($this->request->isAjax()) {
            try {
                $param = $this->request->param();
                $param['rules'] = $param['rules'] ? implode(',', $param['rules']) : '';
                $this->model::update($param);
                return json(['code' => 1, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                return json(['code' => -1, 'msg' => $e->getMessage()]);
            }
        }
        $menu = new \app\common\model\Menu();
        View::assign('list', $menu->getAuth($id));
        return View::fetch();
    }
}
